package com.androidwebapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;

public class MainActivity extends Activity implements LocationListener{

    private WebView myWebView;

    private String result = "";
    private String currentPage = "";
    private String cat = "";
    private String activePage = "";
    private String nid = "";
    private String keyword = "";

    private boolean initApp = false;

    private Tracker mGaTracker;
    private GoogleAnalytics mGaInstance;

    public static final String PREF_FILE_NAME = "PrefFile";
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    Location mostRecentLocation;

    public MainActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_main);

        mGaInstance = GoogleAnalytics.getInstance(this);
        mGaTracker = mGaInstance.getTracker("UA-24886133-5");

        myWebView  = (WebView) findViewById(R.id.webView);

        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setDomStorageEnabled(true);
        myWebView.getSettings().setDatabaseEnabled(true);
        myWebView.getSettings().setDatabasePath("/data/data/"+ getPackageName()+"/databases/");
        if(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
            myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }

        myWebView.addJavascriptInterface(this, "webConnector");

        sharedPreferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
        editor = sharedPreferences.edit();

        myWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                //show loading icon
                myWebView.loadUrl("javascript:jQuery.mobile.showPageLoadingMsg()");
                Boolean getAjax = false;

                currentPage = url;
                result = "";
                String uri = "";

                if(currentPage.indexOf("index.html") > 0){
                    if(!initApp && checkInternetConnection(MainActivity.this)){
                        initApp = true;
                        new updateCacheAll().execute("http://www.ghienkhuyenmai.com/android/all-cache");
                    }
                    mGaTracker.sendView("/home");

                    activePage = "1";
                    if(currentPage.indexOf("page=") > 0){
                        activePage = currentPage.substring(currentPage.indexOf("page=")+5);
                    }

                    result = getPreferences("home:"+activePage);
                    if(!result.equals("") && activePage.equals("1")){
                        myWebView.loadUrl("javascript:loadInfoIndex()");
                        getAjax = false;
                    }
                    else {
                        uri = new String("http://www.ghienkhuyenmai.com/android/index?page="+activePage);
                        getAjax = true;
                    }
                }else if(currentPage.indexOf("detail.html") > 0){
                    nid = currentPage.substring(currentPage.indexOf("detail.html")+16);
                    getAjax = true;

                    mGaTracker.sendView("/detail/"+nid);

                    uri = new String("http://www.ghienkhuyenmai.com/android/detail?nid="+nid);
                }else if(currentPage.indexOf("categories.html") > 0){
                    String[] list = currentPage.split("&");
                    cat = list[0].split("=")[1];
                    activePage = list[1].split("=")[1];

                    result = getPreferences("categories:"+cat+":"+activePage);
                    if(!result.equals("") && activePage.equals("1")){
                        myWebView.loadUrl("javascript:loadInfoCategories()");
                        getAjax = false;
                    }
                    else {
                        uri = new String("http://www.ghienkhuyenmai.com/android/categories?cat="+cat+"&page="+activePage);
                        getAjax = true;
                    }
                    mGaTracker.sendView("/categories/"+cat);
                }else if(currentPage.indexOf("detail-map.html") > 0){
                    nid = currentPage.substring(currentPage.indexOf("nid=")+4);
                    uri = new String("http://www.ghienkhuyenmai.com/android/detail-map?nid="+nid);
                    getAjax = true;
                    mGaTracker.sendView("/maps/"+nid);
                }else if(currentPage.indexOf("search.html") > 0){
                    nid = currentPage.substring(currentPage.indexOf("search=")+7);

                    activePage = "1";
                    if(currentPage.indexOf("page=") > 0){
                        activePage = currentPage.substring(currentPage.indexOf("page=")+5);
                    }

                    String[] list = nid.split("&");

                    keyword = list[0];

                    uri = new String("http://www.ghienkhuyenmai.com/android/search?key="+keyword+"&page="+activePage);
                    getAjax = true;

                    mGaTracker.sendView("/search/"+keyword);
                }else if(currentPage.indexOf("bookmark.html") > 0){

                    result = getPreferences("bookmark");

                    myWebView.loadUrl("javascript:loadInfoBookmark()");
                    if(result.equals("")){
                        MessageBox("Yêu thích", "Chưa có cái nào!");
                    }

                    //hide loading icon
                    myWebView.loadUrl("javascript:jQuery.mobile.hidePageLoadingMsg()");
                    getAjax = false;

                    mGaTracker.sendView("/bookmark");
                }else if(currentPage.indexOf("map.html") > 0){
                	
                	String strLat = "";
                	String strLong = "";
                	if(mostRecentLocation != null) {
                		strLat = getLat();
                		strLong = getLong();
                	}
                	
                    uri = new String("http://www.ghienkhuyenmai.com/android/map?lat="+strLat+"&lng="+strLong);
                    Log.d("abc", uri);

                    getAjax = true;

                    mGaTracker.sendView("/map");
                }

                if (checkInternetConnection(MainActivity.this) && getAjax == true){
                    new ConnectServerSide().execute(uri);
                }else{
                    myWebView.loadUrl("javascript:jQuery.mobile.hidePageLoadingMsg()");
                    if(result.equals("")) {
                        MessageBox("Lỗi kết nối", "Vui lòng kết nối Internet!");
                    }
                }
            }
        });
        myWebView.loadUrl("file:///android_asset/www/index.html?page=1");
    }

    public void MessageBox( String title, String message) {
        AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
        dlgAlert.setMessage(message);
        dlgAlert.setTitle(title);
        dlgAlert.setPositiveButton("OK", null);
        dlgAlert.setCancelable(true);
        dlgAlert.create().show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @JavascriptInterface
    public String getResult() {
        return this.result;
    }

    @JavascriptInterface
    public String getCat() {
        return this.cat;
    }

    @JavascriptInterface
    public String getActivePage() {
        return this.activePage;
    }

    @JavascriptInterface
    public String getKeyword() {
        return this.keyword;
    }

    @JavascriptInterface
    public void addBookmark(String data, String nid, String title) {
        if(checkExistBookmark(nid) == "1"){
            MessageBox("", "khuyen mai nay da duoc chon");
            return;
        }
        String dataFrmt = nid+"###gkm###"+title+"###gkm###"+data + "#@#gkm#@#";
        if(getPreferences("bookmark") != null && !getPreferences("bookmark").equals("")) {
            dataFrmt += getPreferences("bookmark");
            deletePreferences("bookmark");
        }
        SavePreferences("bookmark", dataFrmt);
    }

    @JavascriptInterface
    public String checkExistBookmark(String nid){
        String rtrn = "0";
        String[] bkmrkLst;
        String[] bkmrk;
        String bkmrkInfo = getPreferences("bookmark") ;
        if(bkmrkInfo != null && !bkmrkInfo.equals("")) {
            bkmrkLst = bkmrkInfo.split("#@#gkm#@#");
            for(int i = 0; i < bkmrkLst.length; i++) {
                bkmrk = bkmrkLst[i].split("###gkm###");
                if(bkmrk[0].equals(nid)) {
                    rtrn = "1";
                    break;
                }
            }
        }
        return rtrn;
    }

    @JavascriptInterface
    public void checkdebug(String nmb){
        Log.d("abc", nmb);
    }

    @JavascriptInterface
    public void removeBookmark(String nid) {
        String[] bkmrkLst;
        String[] bkmrk;
        String bkmrkStr = "";
        String bkmrkInfo = getPreferences("bookmark") ;
        if(bkmrkInfo != null && !bkmrkInfo.equals("")) {
            bkmrkLst = bkmrkInfo.split("#@#gkm#@#");
            for(int i = 0; i < bkmrkLst.length; i++) {
                bkmrk = bkmrkLst[i].split("###gkm###");
                if(!bkmrk[0].equals(nid)) {
                    bkmrkStr += bkmrkLst[i]+"#@#gkm#@#";
                }
            }
            SavePreferences("bookmark", bkmrkStr);
        }
    }

    @JavascriptInterface
    public void removeAllBookmark() {
        deletePreferences("bookmark");
    }

    private void getLocation(){
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);

        mostRecentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if(mostRecentLocation == null) {
        	MessageBox("Lỗi kết nối", "Vui lòng bật kết nối GPS!");
        }
    }

    @JavascriptInterface
    public String getLat(){
        getLocation();
        if(mostRecentLocation == null)
        	return "";
        
        return mostRecentLocation.getLatitude()+"";
    }

    @JavascriptInterface
    public String getLong(){
        //getLocation();
        if(mostRecentLocation == null)
        	return "";
        
        return mostRecentLocation.getLongitude()+"";
    }

    public void setCacheHome(String data) {
        deletePreferences("home:1");
        SavePreferences("home:1", data);
    }

    public void setCacheCategory(int tid, String data) {
        deletePreferences("categories:"+tid+":1");
        SavePreferences("categories:"+tid+":1", data);
    }

    private void SavePreferences(String key, String value) {
        editor.putString(key, value);
        editor.commit();
    }

    private void deletePreferences(String key) {
        editor.remove(key);
        editor.commit();
    }


    private String getPreferences(String key){
        return sharedPreferences.getString(key, "");
    }

    public static boolean checkInternetConnection(Context context) {

        ConnectivityManager con_manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (con_manager.getActiveNetworkInfo() != null && con_manager.getActiveNetworkInfo().isAvailable()
                && con_manager.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    private class ConnectServerSide extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... url) {

            InputStream is = null;
            StringBuilder sb = null;

            //http post
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url[0]);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }
            catch(Exception e){
                Log.e("log_tag", "Error in http connection"+e.toString());
            }
            //convert response to string
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                sb = new StringBuilder();
                sb.append(reader.readLine() + "\n");

                String line="0";
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();

                result = sb.toString();
            }
            catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
            }

            return result;
        }

        protected void onPostExecute(String data) {
            if(currentPage.indexOf("index.html") > 0){
                myWebView.loadUrl("javascript:loadInfoIndex()");
                deletePreferences("home:"+activePage);
                SavePreferences("home:"+activePage, data);
            }else if(currentPage.indexOf("detail.html") > 0){
                myWebView.loadUrl("javascript:loadInfoDetail()");
            }else if(currentPage.indexOf("categories.html") > 0){
                myWebView.loadUrl("javascript:loadInfoCategories()");
                deletePreferences("categories:"+cat+":"+activePage);
                SavePreferences("categories:"+cat+":"+activePage, data);
            }else if(currentPage.indexOf("detail-map.html") > 0){
                myWebView.loadUrl("javascript:loadDetailMap()");
            }else if(currentPage.indexOf("search.html") > 0){
                myWebView.loadUrl("javascript:loadInfoSearch()");
            }else if(currentPage.indexOf("map.html") > 0){
               myWebView.loadUrl("javascript:loadMarker()");
                Log.d("abc", data);
            }

            //hide loading icon
            myWebView.loadUrl("javascript:jQuery.mobile.hidePageLoadingMsg()");
        }
    }

    private class updateCacheAll extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... url) {

            InputStream is = null;
            StringBuilder sb = null;

            //http post
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url[0]);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }
            catch(Exception e){
                Log.e("log_tag", "Error in http connection"+e.toString());
            }
            //convert response to string
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                sb = new StringBuilder();
                sb.append(reader.readLine() + "\n");

                String line="0";
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();

                String[] cacheAll = sb.toString().split("###");
                int i = 0;
                while(i < cacheAll.length){
                    switch (i) {
                        case 0:
                            setCacheHome(cacheAll[i]);
                            break;
                        case 1:
                            setCacheCategory(2, cacheAll[i]);
                            break;
                        case 2:
                            setCacheCategory(3, cacheAll[i]);
                            break;
                        case 3:
                            setCacheCategory(1, cacheAll[i]);
                            break;
                        case 4:
                            setCacheCategory(213, cacheAll[i]);
                            break;
                        case 5:
                            setCacheCategory(6, cacheAll[i]);
                            break;
                        case 6:
                            setCacheCategory(5, cacheAll[i]);
                            break;
                        case 7:
                            setCacheCategory(392, cacheAll[i]);
                            break;
                        case 8:
                            setCacheCategory(4, cacheAll[i]);
                            break;
                        case 9:
                            setCacheCategory(1434, cacheAll[i]);
                            break;
                    }

                    i++;
                }
            }
            catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
            }

            return "";
        }
    }
}
